<?php
// 应用公共文件
use jwt\JWT;
use think\facade\Db;
use think\response\Json;

/**
 * @Notes: 统一返回值
 * @Interface rejson
 * @param int $code 状态码
 * @param string $msg 返回信息
 * @param array $data 返回数据
 * @param string $ext 备用字段
 * @return Json
 * @author: Shaco
 * @Time: 2022/8/23-21:35
 */
function rejson ($code = 0, $msg = '', $data = [], $ext = '')
{
    return json(['code' => $code, 'msg' => $msg, 'data' => $data, 'ext' => $ext]);
}

/**
 * @Notes: 封装token
 * @Interface settoken
 * @param $token
 * @return string
 * @author: Shaco
 * @Time: 2022/8/23-21:38
 */
function settoken($token)
{
    $key = 'keep_online';
    return JWT::encode($token, $key);
}

/**
 * @Notes: 解析token
 * @Interface explaintoken
 * @param $str
 * @return object
 * @author: Shaco
 * @Time: 2022/8/23-21:38
 */
function explaintoken($str)
{
    $key = 'keep_online';
    return JWT::decode($str, $key, array('HS256'));
}

/**
 * @Notes: 签发token
 * @Interface login_token
 * @param $id
 * @return string
 * @author: Shaco
 * @Time: 2022/8/23-21:38
 */
function login_token($id)
{
    $iat = time(); //签发时间
    $exp = $iat + 86400 * 31; //过期时间31天
    $token = array(
        "iss" => "http://api.helii.com",
        "aud" => "http://sso.helii.com",
        "iat" => $iat,
        "exp" => $exp,
        "id" => $id
    );

    return settoken($token);
}

/**
 * @Notes: 检验token
 * @Interface check_login
 * @param $token
 * @return array|int
 * @author: Shaco
 * @Time: 2022/8/23-21:38
 */
function check_login($token)
{
    if (!$token) return 0;

    try {
        $token = explaintoken($token);
        $uid = $token->id;
        return Db::name('user')->where('id', $uid)->find();
    } catch (Exception $e) {
        return [];
    }
}

/**
 * @Notes: 扁平数组转树
 * @Interface array_to_tree
 * @param array $list 数组
 * @param string $pk 主键
 * @param string $pid 父级id键名
 * @param string $child 子节点键名
 * @param int $root 判断根节点依据
 * @return array
 * @author: Shaco
 * @Time: 2022/8/23-22:24
 */
function array_to_tree(array $list, string $pk = 'id', string $pid = 'pid', string $child = 'children', int $root = 0)
{
    $tree = array();
    $packData = array();
    foreach ($list as $data) {
        $packData[$data[$pk]] = $data;
    }
    foreach ($packData as $key => $val) {
        if ($val[$pid] == $root) {
            $tree[] = &$packData[$key];
        } else {
            $packData[$val[$pid]][$child][] = &$packData[$key];
        }
    }
    return $tree;
}

/**
 * @Notes: 日志打印
 * @Interface log2
 * @param string $content 日志内容
 * @author: Shaco
 * @Time: 2022/8/24-23:13
 */
function log2(string $content)
{
    //日志目录,根据自己的需求修改,也可以不要
    $directory = __DIR__.'log/';

    if(!is_readable($directory))
    {
        mkdir($directory,0700);
    }

    $filename = $directory.date('Y.m.d').'.log';
    $fp = fopen($filename, 'a+');
    fwrite($fp,date('Y-m-d H:i:s').' '.$content."\r");
    fclose($fp);
}

function img($fileArr,$file){
    /**
     * 判断接收文件是否为空
     */
    if($fileArr == null){
        return rejson(0, "未上传图片");
    }
    /**
     * 截取上传文件名后缀
     * 将文件名以.分割为数组
     * 用PHP end函数取数组最后一个
     * 即可得到上传文件后缀 $temp = explode(".", $_FILES["file"]["name"]);
     */
    $temp = explode(".",$file["name"]);
    $extension = strtolower(end($temp));
    /**
     * 判断上传文件是否合法
     * 判断截取上传文件名是否为
     * jpeg，jpg，png其中之一
     */
    if(!in_array($extension,array("jpeg","jpg","png","webp"))){
        return rejson(0, "上传图片不合法");
    }
    /**
     * 调用disk方法
     * 此时根目录为/public/storage 系统默认路径
     * 再把文件移动至uploads下的img文件夹里
     * 文件名用data
     */
    $saveName = \think\facade\Filesystem::disk('upload')->putFile('upload',$fileArr,'data');
    return $saveName;
}
function howOld($birth) {
    list($birthYear, $birthMonth, $birthDay) = explode('-', date('Y-m-d', $birth));
    list($currentYear, $currentMonth, $currentDay) = explode('-', date('Y-m-d'));
    $age = $currentYear - $birthYear - 1;
    if($currentMonth > $birthMonth || $currentMonth == $birthMonth && $currentDay >= $birthDay)
        $age++;

    return $age;
}
